package com.robot.backend.service.impl.user;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.robot.backend.mapper.UserMapper;
import com.robot.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.robot.backend.service.user.userInfoService;

import java.util.List;
import java.util.Map;

@Service
public class userInfoServiceImpl implements userInfoService{
    @Autowired
    UserMapper userMapper;

    @Override
    public String userInfoGet() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User user = userMapper.selectById(StpUtil.getLoginId().toString());
        if(user.getId() == StpUtil.getLoginId()) return null;//安全性检查，一个用户无法查询另一个用户的信息
        return JSON.toJSONString(user);
    }

    @Override
    public String userInfoUpdate(String name,String photo) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        User t = userMapper.selectOne(queryWrapper);
        if(t!=null && t.getId() != StpUtil.getLoginIdAsInt()) return "error";
        User user = userMapper.selectById(StpUtil.getLoginId().toString());
        if(!photo.isEmpty()) user.setPhoto(photo);
        user.setName(name);
        if(user.getId() == StpUtil.getLoginId()) return null;//安全性检查，一个用户无法更新另一个用户的信息
        userMapper.updateById(user);
        return "success";
    }

    @Override
    public String tokenInfo() {
        User user = userMapper.selectById(StpUtil.getLoginId().toString());
        return JSON.toJSONString(user);
    }

    @Override
    public JSONObject userRank(int page,int size) {
        JSONObject jsonObject = new JSONObject();
        IPage<User> iPage = new Page<>(page,size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("score");
        List<User> list = userMapper.selectPage(iPage,queryWrapper).getRecords();
        jsonObject.put("user",list);
        jsonObject.put("length",userMapper.selectCount(null));
        return jsonObject;
    }
}
